package cn.hanyx.coder.core.concurrent.rw;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * RWSample
 *
 * @author hanyx
 * @date 2020/05/29
 */
public class RWSample {
    private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private final Lock readLock = readWriteLock.readLock();
    private final Lock writeLock = readWriteLock.writeLock();
    private final Map<String, String> map = new HashMap<>();
    public String get(String key) {
        readLock.lock();
        try {
            System.out.println("读锁锁定！");
            return this.map.get(key);
        } finally {
            readLock.unlock();
        }
    }
    public void put(String key, String val) {
        writeLock.lock();
        try {
            System.out.println("写锁锁定！");
            this.map.put(key, val);
        } finally {
            writeLock.unlock();
        }
    }

    public static void main(String[] args) throws Exception {
        RWSample rw = new RWSample();
        Thread thread01 = new Thread(() -> {
            rw.put("aaa", "aaa");
        });
        Thread thread02 = new Thread(() -> {
            rw.put("bbb", "bbb");
        });
        Thread thread03 = new Thread(() -> {
            System.out.println(rw.get("aaa"));
        });
        thread01.start();
        thread02.start();
        thread03.start();
        thread01.join();
        thread02.join();
        thread03.join();
    }
}
